package com.zyg.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.dao.RoleMapper;
import com.zyg.pojo.Role;
import com.zyg.pojo.RolePermission;
import com.zyg.service.RolePermissionService;
import com.zyg.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    @Transactional
    public boolean save(Role role) {
        int result = baseMapper.insert(role);
        // 保存用户的权限
        // 获取主键
        Integer rId = role.getRoleId();
        Integer[] pIds = role.getPIds();
        // 构建角色权限集合对象
        List<RolePermission> rolePermissionList = new ArrayList<>();
        if (pIds != null && pIds.length > 0){
            for (Integer pId : pIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRId(rId);
                rolePermission.setPId(pId);
                rolePermissionList.add(rolePermission);
            }
            rolePermissionService.saveBatch(rolePermissionList);
        }
        return result > 0;
    }
}
